package com.korion.aidldemo

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.IBinder
import android.util.Log
import android.widget.Toast
import com.korion.aidldemo.im.*
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity(), IMessageListener {

    private var mClient: Client? = null
    private var mServer: IServer? = null

    companion object {
        const val TAG = "MainActivity"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        btn1.setOnClickListener {
            launchRemoteProcessService()
        }
        btn2.setOnClickListener {
            val text = edt_content.text.toString().trim()
            val msg = Message(Message.CUSTOM, text)
            mServer?.sendMessage(msg)
        }
        btn3.setOnClickListener {
            val msg = Message(Message.START_CALL_CLIENT, "")
            mServer?.sendMessage(msg)
        }
    }

    private fun launchRemoteProcessService() {
        val intent = Intent(this, RemoteProcessService::class.java)
        startService(intent)
        bindService(intent, object : ServiceConnection{
            override fun onServiceDisconnected(name: ComponentName?) {

            }

            override fun onServiceConnected(name: ComponentName?, server: IBinder?) {
                var result:Boolean? = false
                if (server != null){
                    mClient = Client(server, Handler())
                    mClient?.setMessageListener(this@MainActivity)
                    mServer = mClient!!.server
                    result = mServer?.registerClient(mClient)
                }
                if (result != true){
                    Log.e(TAG, "绑定远程服务失败")
                }
            }
        }, Context.BIND_AUTO_CREATE)
    }

    override fun onMessageReceivce(message: Message?) {
        /*message?.run {
            showToast("Client rev: ${this.payload}")
        }*/
        Log.d(TAG, "client rev: ${message?.payload}, thread: ${Thread.currentThread().name}")
    }
}

fun Context.showToast(message: String){
    Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}